<?php
namespace Home\Controller;
use Home\Model\OrderModel;
use Home\Model\ClassModel;
import('Vendor.Alipay.alipaySubmit','','.php');
/**
 * 支付控制器
 *  
 */
class PaymentController extends BaseController{
 
    
    private $payId='';  //微支付公众号APPID
    private $mchId='';  //微支付商户ID
    private $apiKey=''; //微支付密钥
    
    /**
     * 构造函数
     */
    public function __construct(){
        parent::__construct();
        $this->payId=C('APPID');
        $this->mchId=C('Mchid');
        $this->apiKey=C('Apikey');
    }
    /**
     * 开始支付
     */
    public function wechatpay(){
        header("Content-Type:text/html;charset=utf-8");
        $redirectUrl="http://m.91eshixi.com/index.php?s=/Index/mycourse.html";
        //读取到微信支付的配置，appid  mchid,apikey
        $orderid=intval(I("orderid"));
        if(empty($orderid)||$orderid==0){
            $this->error("订单不存在，请重新支付！");
        }
        $orderModel=new OrderModel();
        $orderwhere['id']=$orderid;
        $orderInfo=$orderModel->getorderItem($orderwhere);
        if(empty($orderInfo)){
            $this->error("订单不存在，请重新支付！");
        }
        $ps = array();
        $ps['ordersn'] = $orderInfo['ordersn'];
        $ps['type'] = "E课堂";
        $ps['fee'] =$orderInfo['money'];
        $ps['title'] = "E课堂订单";
        $ps['openid']=$this->_openid;
        $wechat['appid']=trim($this->payId);
        $wechat['mchid']=trim($this->mchId);
        $wechat['apikey']=trim($this->apiKey);
        $wOpt = $this->wechat_buildAction($ps, $wechat);
        //支付报错
        if (is_error($wOpt)) {
            $this->error("抱歉，发起支付失败，具体原因为：“{$wOpt['errno']}:{$wOpt['message']}”。请及时联系站点管理员。");
            exit;
        }   
        echo "
                <script type='text/javascript'>
                document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
                    WeixinJSBridge.invoke('getBrandWCPayRequest', {
                        'appId' : '".$wOpt['appId']."',
                        'timeStamp': '".$wOpt['timeStamp']."',
                        'nonceStr' : '".$wOpt['nonceStr']."',
                        'package' : '".$wOpt['package']."',
                        'signType' : '".$wOpt['signType']."',
                        'paySign' : '".$wOpt['paySign']."'
                    }, function(res) {
                        if(res.err_msg == 'get_brand_wcpay_request:ok') {
                            alert('该订单您已支付成功！');
                            location.href='".$redirectUrl."';
                        }else if(res.err_msg == 'get_brand_wcpay_request:cancel'){
                            alert('该订单您已取消支付！');
                            location.href='".$redirectUrl."';
                        }else{
                            history.go(-1);
                            alert('启动微信支付失败, 请检查你的支付参数. 详细错误为: ' + res.err_msg);
                        }
                    });
                }, false);
                </script>";
            exit();
    }
    /**
     * 微信支付回调函数
     */
    public function wechat_notify(){
        M('Cate')->add(array('name'=>'一个让人发指的女人'));
        $input = file_get_contents('php://input');
        if (!empty($input) && empty($_GET['out_trade_no'])) {
            $obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
            $data = json_decode(json_encode($obj), true);
            if (empty($data)) {
                exit('fail');
            }
            if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS') {
                exit('fail');
            }
            $params = $data;
        } else {
            $params = I();
        }
        if(is_array($params)){
            ksort($params);
            $ordersn=strval($params['out_trade_no']);
            $orderModel=new OrderModel();
            $orderwhere['ordersn']=$ordersn;
            $orderInfo=$orderModel->getorderItem($orderwhere);
            if(!empty($orderInfo)&&$orderInfo['status']==2){
               $data['transid']=$params['transaction_id'];
               $data['status']=1;
                $result=$orderModel->uporder($orderwhere,$data);
                $ret = array();
                $ret['result'] = 'success';
                $ret['from'] = 'notify';
                $ret['orderid']=$orderInfo['id'];
                $this->payResult($ret);
                exit();
             }
        }
    }
    /**
     * 微信支付返回函数
     */
     public function wechat_return(){
        $pars=I('ps');
        $params = @json_decode(base64_decode($pars), true);
        $tid=strval($params['out_trade_no']);
         $ordersn=strval($params['out_trade_no']);
         $orderModel=new OrderModel();
         $orderwhere['ordersn']=$ordersn;
         $orderInfo=$orderModel->getorderItem($orderwhere);
         if(!empty($orderInfo)&&$orderInfo['status']==2){
             $data['transid']=$params['transaction_id'];
             $data['status']=1;
             $result=$orderModel->uporder($orderwhere,$data);
             $ret = array();
             $ret['result'] = 'success';
             $ret['from'] = 'notify';
             $ret['orderid']=$orderInfo['id'];
             $this->payResult($ret);
             exit();
         }
    } 
 
    /**
     * 微信支付
     * @param  $params 支付参数
     * @param  $wechat 配置参数
     * @return multitype:string number |Ambigous <multitype:unknown string , multitype:unknown string Ambigous <> Ambigous <boolean, string> >|multitype:unknown string |multitype:string unknown number
     */
    protected function wechat_buildAction($params, $wechat) {
        $apikey=trim($this->apiKey);
        $package['appid'] =$wechat['appid'];
        $package['mch_id'] =$wechat['mchid'];
        $package['nonce_str'] =random(8);
        $package['body'] = $params['type'];
        $package['out_trade_no'] =$params['ordersn'];
        $package['total_fee'] =$params['fee'] * 100;
        $package['spbill_create_ip'] =get_client_ip();
        $package['time_start'] =time();
        $package['time_expire'] =date('YmdHis', time() + 600);
        $package['notify_url'] ="http://".$_SERVER["SERVER_NAME"]."/?module=Home&controller=Payment&action=wechat_notify";
        $package['trade_type'] ='JSAPI';
        $package['openid']=$params['openid'];
        print_R($package);exit();
        
        
     //   echo 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];die;
        ksort($package, SORT_STRING);
        $string1 = '';
        foreach($package as $key => $v) {
            if (empty($v)) {
                continue;
            }
            $string1 .= "{$key}={$v}&";
        }
        $string1 .= "key={$apikey}";
        $package['sign'] = strtoupper(md5($string1));
        $dat = array2xml($package);
        $response = ihttp_request('https://api.mch.weixin.qq.com/pay/unifiedorder', $dat);
            if (is_error($response)) {
            return $response;
            }
            $xml = @simplexml_load_string($response['content'], 'SimpleXMLElement', LIBXML_NOCDATA);
            if (strval($xml->return_code) == 'FAIL') {
            return error(-1, strval($xml->return_msg));
            }
            if (strval($xml->result_code) == 'FAIL') {
                return error(-1, strval($xml->err_code).': '.strval($xml->err_code_des));
            }
            $prepayid = $xml->prepay_id;
            $wOpt['appId'] = $wechat['appid'];
            $wOpt['timeStamp'] = time();
            $wOpt['nonceStr'] = random(8);
            $wOpt['package'] = 'prepay_id='.$prepayid;
            $wOpt['signType'] = 'MD5';
            ksort($wOpt, SORT_STRING);
            foreach($wOpt as $key => $v) {
                $string .= "{$key}={$v}&";
            }
            $string .= "key={$wechat['apikey']}";
            $wOpt['paySign'] =strtoupper(md5($string));
            
            return $wOpt;
    }
    /**
     * 支付完   成处理
     * @param   $ret
     */
    public function payResult($ret){
        //  根据classid修改收听人数+1
        $orderModel=new OrderModel();
        $classModel=new ClassModel();
        $orderid=$ret['orderid'];
        $orderwhere['id']=$orderid;
        $orderInfo=$orderModel->getorderItem($orderwhere);
        $classid=intval($orderInfo['class_id']);
        $classwhere['id']=$classid;
        $classInfo=$classModel->getClassItem($classwhere);
        $listennum=$classInfo['listennum'];
        $listennum=$listennum+1;
        $data['listennum']=$listennum;
        $result=$classModel->upClass($classwhere,$data);
    }
    

}